import {
  createRouter as createVueRouter,
  createMemoryHistory,
  createWebHistory,
  type RouteLocation,
} from 'vue-router';
import type { I18n } from '../i18n';
import { setTitleForClient } from '../utils/other';
import type { Pinia } from 'pinia';
import { useAppStore } from '@/mobile/stores/app';
import { $fetch } from '../utils/fetch';
import { HEADER_KEY_COMMUNITY, HEADER_KEY_LANGUAGE, HEADER_KEY_TOKEN } from '@/common/utils/constants';
import { getDeviceId } from '@/common/utils/stats';
import { useWeChatShare } from '@/mobile/hooks/wechat-share';

export interface RouterOptions {
  i18n: I18n,
  pinia: Pinia,
  language: string,
  communityName: string,
  token: string,
}

export function createRouter({ pinia, language, communityName, token }: RouterOptions) {
  // const isZh = i18n.global.locale.value === 'zh-CN';

  // 定义路由，注意：不建议使用 name 属性
  // 因为多语言的关系，一定要在 createRouter 内部定义路由

  // meta.autoSetTitle 传递 false 表示标题由组件直接控制，导航守卫不进行干预，如果组件不控制，则标题不变

  const routes = [
    {
      path: '/',
      component: () => import('../views/home/index.vue'),
      meta: {
      },
    },

    {
      path: '/explore/journalism/detail/:id',
      component: () => import('../views/home/detail.vue'),
      props: (route: RouteLocation) => ({ id: route.params.id, pageType: 'detail' }),
      meta: {
        autoSetTitle: false,
      },
    },

    // 承载 PC 端的页面，因为如果把 PC 端相应的页面直接放到手机上，会导致 404，所以需要一个过度方式
    {
      path: '/explore/journalism/:type?/:page?',
      redirect: '/',
    },
    {
      path: '/explore/organization/:type?/:page?',
      redirect: '/',
    },
    {
      path: '/explore/developer/:page?',
      redirect: '/',
    },
    {
      path: '/explore/repository/:type?/:page?',
      redirect: '/',
    },
    {
      path: '/explore/journalism/preview/:id',
      redirect: '/',
    },
    // TODO: 退订页面看看是不是要做移动端
    {
      path: '/subscription/unsubscribe',
      redirect: '/',
    },
    {
      path: '/search',
      redirect: '/',
    },
    {
      path: '/tag/:id/:type?',
      redirect: '/',
    },
    {
      path: '/column/detail/:id',
      redirect: '/',
    },

    // 注意：404 路由，业务路由都要放在这前面
    {
      path: '/:pathMatch(.*)*',
      alias: '/404',
      component: () => import('../views/common/404.vue'),
      meta: {
        title: '404 Not Found',
      },
    },
  ];

  const router = createVueRouter({
    history: import.meta.env.SSR ? createMemoryHistory(import.meta.env.MICRO_SITE_BASE_URL) : createWebHistory(import.meta.env.MICRO_SITE_BASE_URL),
    routes,
    scrollBehavior(to, from, savedPosition) {
      if (savedPosition && to.path === '/') {
        return savedPosition;
      }
      else {
        return { top: 0 };
      }
    },
  });

  router.beforeEach((to) => {
    if (!import.meta.env.SSR) {
      if (to.meta.autoSetTitle !== false) {
        const store = useAppStore(pinia);

        setTitleForClient(to.meta.title as string, store.config.seo.title || store.config.name);
      }
    }
  });

  const configureWeChatSDK = async () => {
    try {
      const { isSuccess, data } = await $fetch('/wechat/getSignature', {
        method: 'post',
        data: {
          url: window.location.href,
        },
      });

      if (isSuccess) {
        window.wx.config({
          debug: false,
          appId: data.appId,
          timestamp: data.timestamp,
          nonceStr: data.nonceStr,
          signature: data.signature,
          jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'],
        });
      } else {
        throw new Error('获取签名失败或数据无效');
      }
    } catch (error) {
      console.error('微信SDK配置失败:', error);
    }
  };

  router.afterEach((to) => {
    if (!import.meta.env.SSR) {
      // 统计埋点
      const headers: Record<string, any> = {
        [HEADER_KEY_COMMUNITY]: communityName,
        [HEADER_KEY_LANGUAGE]: language,
      }
      token && (headers[HEADER_KEY_TOKEN] = token);
      $fetch('/record/doRecord', {
        method: 'post',
        headers,
        data: {
          deviceId: getDeviceId(),
        },
      });

      if (window._oafs) {
        if (to.meta.lazyStats !== true) {
          setTimeout(() => {
            window._oafs.setDefault('pageId', document.title);
            window._oafs.pv();
          });
        }
      }

      if (window._hmt) {
        setTimeout(() => {
          window._hmt.push(['_trackPageview', to.path]);
        });
      }

      if (window.wx) {
        const store = useAppStore(pinia);
        const communityInfo = store.config;
        const { setShareData } = useWeChatShare();
        configureWeChatSDK();
        setShareData({ title: communityInfo.name, desc: communityInfo.description, img: communityInfo.logo })
      }
    }
  });

  return router;
}
